﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Tulde.Windows.Music.ViewModel;
using Tulde.Windows.Music;
using System.Windows.Threading;
using System.Windows.Media.Effects;
using Tulde.Windows.Amazon;
using Tulde.Windows.App;


namespace MP3Tunes.WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
      
        DispatcherTimer timer;

        private Mp3TunesCredentials credentials;


        private List<Track> currentTrackList;
        protected Track SelectedTrack
        {
            get
            {
                return this.listTracks.SelectedItem as Track;
            }
        }
        protected Album SelectedAlbum
        {
            get
            {
                return this.listAlbums.SelectedItem as Album;
            }
        }
        protected Artist SelectedArtist
        {
            get
            {
                return this.listArtists.SelectedItem as Artist;
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(200);
            timer.Tick += new EventHandler(timer_Tick);

       
           
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            this.listArtists.SelectionChanged += new SelectionChangedEventHandler(listArtists_SelectionChanged);
            this.listAlbums.SelectionChanged += new SelectionChangedEventHandler(listAlbums_SelectionChanged);
            this.listTracks.SelectionChanged += new SelectionChangedEventHandler(listTracks_SelectionChanged);
            this.mediaPlayer1.TrackChanged += new EventHandler<Tulde.Windows.App.Controls.MediaPlayerEventArgs>(mediaPlayer1_TrackChanged);
            this.shuffleSongs.Click += new RoutedEventHandler(shuffleSongs_Click);
          
        }

        void shuffleSongs_Click(object sender, RoutedEventArgs e)
        {
            ResetSelections();
            this.mediaPlayer1.SetProgressBar(true);
            MusicServiceFactory.Instance.GetPlaylist(new ShufflePlaylist(), tracks =>
            {

                this.currentTrackList = new List<Track>();
                this.currentTrackList.AddRange(tracks.Tracks);
                this.listTracks.DataContext = this.currentTrackList;
                Cursor = Cursors.Arrow;
                this.mediaPlayer1.TrackCollection = this.currentTrackList;

                borderAlbumArt.Visibility = System.Windows.Visibility.Visible;

                this.mediaPlayer1.SetProgressBar(false);
            });

            

            
        }

        void mediaPlayer1_TrackChanged(object sender, Tulde.Windows.App.Controls.MediaPlayerEventArgs e)
        {
            this.SetCurrentTrack(e.Track);
            this.SetDisplayBackground(e.Track);
            
         
             
        }

      

     

       

        
      

       

        void timer_Tick(object sender, EventArgs e)
        {
           
        }



       

        private void ResetSelections()
        {
            this.listTracks.DataContext = null;
            this.albumArt.Source = null;
            borderAlbumArt.Visibility = System.Windows.Visibility.Hidden;
            this.listAlbums.DataContext = null;
            this.artistNameText.Text = "";
            this.albumNameText.Text = "";
            this.rightGrid.Background = null;
        }
       
       
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {

          
            this.credentials = (Mp3TunesCredentials)SecurityProvider.LoadCredentials();
            if (this.credentials == null)
            {
                Credentials c = new Credentials();
                c.ShowInTaskbar = true;
                c.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                if (c.ShowDialog().HasValue )
                {

                    this.credentials = (Mp3TunesCredentials)c.SelectedCredentials;
                    SecurityProvider.SaveCredentials(this.credentials);
                }
            }
            this.mediaPlayer1.SetProgressBar(true);
            Cursor = Cursors.Wait;
            MusicServiceFactory.Instance.Authenticate(this.credentials, token =>
            {
                SecurityProvider.SetAuthenticationTokens(token);
                MusicServiceFactory.Instance.EnumerateArtists(tracks =>
                {
                    this.listArtists.DataContext = tracks.Artists;
                    Cursor = Cursors.Arrow;
                    this.mediaPlayer1.SetProgressBar(false);
                });
            });
        }

       


        #region Control Event Handlers
        void listArtists_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.SelectedArtist == null)
            {
                return;
            }
            this.mediaPlayer1.SetProgressBar(true);
            this.ResetSelections();
            var artist = this.listArtists.SelectedItem as Artist;
            MusicServiceFactory.Instance.GetArtistAlbums(artist, tracks =>
            {
                this.listAlbums.DataContext = tracks.Albums;
                Cursor = Cursors.Arrow;
                this.mediaPlayer1.SetProgressBar(false);
            });
        }
        private void SetTrackView(TrackCollection tracks)
        {
           
        }

        void listAlbums_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (this.SelectedAlbum == null)
            {
                return;
            }
            var album = this.listAlbums.SelectedItem as Album;

            this.mediaPlayer1.SetProgressBar(true);
            this.listTracks.DataContext = null;
            this.albumArt.Source = null;
            borderAlbumArt.Visibility = System.Windows.Visibility.Hidden;
            MusicServiceFactory.Instance.GetAlbumTracks(album, tracks =>
            {
                this.currentTrackList = new List<Track>();
                this.currentTrackList.AddRange(tracks.Tracks);
                this.listTracks.DataContext = this.currentTrackList;
                Cursor = Cursors.Arrow;
                this.mediaPlayer1.TrackCollection = this.currentTrackList;

                borderAlbumArt.Visibility = System.Windows.Visibility.Visible;
                //this.albumNameText.Text = album.AlbumTitle;
                //this.artistNameText.Text = this.SelectedArtist.ArtistName;
                this.mediaPlayer1.SetProgressBar(false);
            });
        }
        void listTracks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.SelectedTrack == null)
            {
                return;
            }
            this.albumNameText.Text = this.SelectedTrack.AlbumTitle;
            this.artistNameText.Text = this.SelectedTrack.ArtistName;
            this.mediaPlayer1.PlayTrack(this.SelectedTrack);
            

        }
       

        #endregion

        #region Set Methods
        private void SetCurrentTrack( Track track)
        {
            this.listTracks.SelectedValue = track;
        }
        private void SetDisplayBackground(Track track)
        {
            this.albumArt.Source = null;
            ImageBrush backgroundBrush = null;
           
            var urls = AlbumArtService.Locate(new AmazonCredentials(), track.AlbumTitle, track.ArtistName);

            backgroundBrush = new ImageBrush(
                     !String.IsNullOrEmpty(urls.LargeUrl) ?
                        AlbumArtResource.Load(urls.LargeUrl) :
                        AlbumArtResource.Load(new Album { AlbumId = track.AlbumId })
                );
            backgroundBrush.Opacity = 0.20;
            backgroundBrush.Stretch = Stretch.Fill;
  
            this.rightGrid.Background = backgroundBrush;
            //this.backgroundArt.ImageSource = !String.IsNullOrEmpty(urls.Large) ?
            //            AlbumArtResource.Load(urls.Large) :
            //            AlbumArtResource.Load(new Album { AlbumId = track.AlbumId });
           

            this.albumArt.Source = String.IsNullOrEmpty(urls.SmallUrl) ?
                AlbumArtResource.Load(new Album { AlbumId = track.AlbumId }) :
                AlbumArtResource.Load(urls.SmallUrl);

          
        }
        #endregion

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.searchPattern.Text))
            {
                MessageBox.Show("Please enter a search pattern.");
                e.Handled = true;
                return;
            }
            this.mediaPlayer1.SetProgressBar(true);
            MusicServiceFactory.Instance.SearchArtists(this.searchPattern.Text, results =>
                {
                    this.listArtists.DataContext = results.ArtistList;
                    Cursor = Cursors.Arrow;
                    this.mediaPlayer1.SetProgressBar(false);
                });
        }
        private void clearButton_Click(object sender, RoutedEventArgs e)
        {
            this.mediaPlayer1.SetProgressBar(true);
            MusicServiceFactory.Instance.EnumerateArtists(tracks =>
            {
                this.listArtists.DataContext = tracks.Artists;
                Cursor = Cursors.Arrow;
                this.mediaPlayer1.SetProgressBar(false);
            });
        }
    }
}
